package org.example.service.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import kuaizu.common.mqconst.MQConstant;
import kuaizu.common.param.NoAuditProjectParam;
import kuaizu.common.param.PromotionInfoParam;
import kuaizu.common.param.UpdateAuditStatusParam;
import kuaizu.common.param.projectReviewMassageParam;
import kuaizu.common.tablepojo.Project;
import kuaizu.common.tablepojo.ProjectAudit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.exception.exception.MassageException;
import org.example.mapper.ProjectMapper;
import org.example.mapper.UserMapper;
import org.example.pojo.PromotionInfoIdsParam;
import org.example.pojo.Result;
import org.example.pojo.User;
import org.example.pojo.vo.ProjectInfoOv;
import org.example.pojo.vo.SchoolMajorCountDtoListOv;
import org.example.service.ProjectService;
import org.example.utils.HttpRequestUtil;
import org.example.utils.KuaiZuConst;
import org.example.utils.LogInfoUtil;
import org.example.utils.ThreadLocalUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class ProjectServiceImpl implements ProjectService {

    private final HttpRequestUtil httpRequestUtil;
    private final ProjectMapper projectMapper;
    private final UserMapper userMapper;
    private final ObjectMapper objectMapper;

    //根据id列表查询项目详情
    @Override
    @Transactional
    public ProjectInfoOv selectById(PromotionInfoIdsParam param) {
        //查询数据库获取标记项目id
        ProjectInfoOv pb = httpRequestUtil.postRequest(
                //"/email/promotionProjectByIds",//请求路径
                "/email/promotionProjectByIds",
                param,//请求参数,注意要跟接口文档的参数保持一致
                new ProjectInfoOv(),//请求蚕食返回值封装的对象
                ProjectInfoOv.class//对象字节码文件
                //返回参数  []
        );
        pb.setPageSize(param.getPageSize());
        pb.setPageNum(param.getPageNum());
        return pb;
    }

    //查询项目信息
    @Override
    @Transactional
    public ProjectInfoOv promotionInfo(PromotionInfoParam param) {
        ProjectInfoOv pb = httpRequestUtil.postRequest("/email/promotionProject", param, new ProjectInfoOv(), ProjectInfoOv.class);
        pb.setPageSize(param.getPageSize());
        pb.setPageNum(param.getPageNum());
        return pb;
    }

    //标记项目
    @Override
    @Transactional
    public Object markProject(Integer projectId) {
        //将项目id存储到数据库中
        //从ThreadLocalUtil获取操作人的信息
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        User user = userMapper.queryUserByUserId((Integer) userInfo.get("id"));
        //判断标记项目是否有数据
        if (null == user.getMarkedProjects() || KuaiZuConst.STRING_EMPTY.equals(user.getMarkedProjects())) {
            //首次标记项目
            StringBuilder sb = new StringBuilder();
            sb.append("[").append(projectId.toString()).append("]");
            user.setMarkedProjects(sb.toString());
            //存储到数据库中
            userMapper.updateUserMarkProject(user.getId(), sb.toString());
        } else {
            //表示用户标记过项目截取掉最后一个字符串
            //判断是否标记过该项目
            if (user.getMarkedProjects().contains(projectId.toString())) {
                //抛出异常
                throw new RuntimeException(KuaiZuConst.STRING_REPEAT);
            }
            StringBuilder sb = new StringBuilder(user.getMarkedProjects().substring(0, user.getMarkedProjects().length() - 1));
            sb.append(",").append(projectId.toString()).append("]");
            //存储到数据库中
            userMapper.updateUserMarkProject(user.getId(), sb.toString());
        }
        return "标记成功";
    }

    //取消标记项目
    @Override
    @Transactional
    public Object cancelMarkProject(Integer projectId) {
        Map<String, Object> userInfo = ThreadLocalUtil.get();
        User user = userMapper.queryUserByUserId((Integer) userInfo.get("id"));
        //判断是否标记过该项目
        if (!user.getMarkedProjects().contains(projectId.toString())) {
            //抛出异常
            throw new RuntimeException(KuaiZuConst.STRING_REPEAT);
        }
        Set<String> list = new HashSet<>(Arrays.asList(user.getMarkedProjects().substring(1, user.getMarkedProjects().length() - 1).trim().split(",")));
        //遍历数组去掉制定的数据
        log.info("几何数据{}", list);
        list.remove(projectId.toString());
        //将集合转换为字符串
        String s = list.stream().collect(Collectors.joining(","));
        //添加括号
        StringBuilder sb = new StringBuilder();
        sb.append("[").append(s).append("]");
        //更新数据库
        userMapper.updateUserMarkProject(user.getId(), sb.toString());
        return sb.toString();
    }

    @Override
    @Transactional
    public SchoolMajorCountDtoListOv getSchoolStudentInfo() {
        SchoolMajorCountDtoListOv schoolMajorCountDtoListOv = httpRequestUtil.postRequest("/hou/getSchoolStudentInfo", null, new SchoolMajorCountDtoListOv(), SchoolMajorCountDtoListOv.class);
        return schoolMajorCountDtoListOv;
    }

    //获取指定专业注册人信息
    @Override
    @Transactional
    public Object getMajorStudentInfo() {

        return null;
    }

    private final RabbitTemplate rabbitTemplate;

    @Transactional
    @Override
    public void updateAuditStatus(UpdateAuditStatusParam param) {
        Date date = new Date();
        String s = null;
        try {
            Map<String, Object> o = ThreadLocalUtil.get();
            s = objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            throw new MassageException("用户信息异常,尝试重新登陆");
        }
        ProjectAudit proInfo = new ProjectAudit();
        BeanUtils.copyProperties(param, proInfo);
        //将map转成json对象
        proInfo.setAuditUserInfo(s);//设置姓名
        proInfo.setAuditTime(date);//设置审核时间
        Result result = httpRequestUtil.postRequest("/hou/project/audit", param, new Result(), Result.class);
        if (!ObjectUtils.isEmpty(result) && result.getCode() == 200) {
            projectMapper.insertProjectProofStart(proInfo);
            String data = "审核未通过";
            if (param.getAuditStatus()) {
                data = "审核通过";
            }
            userMapper.insertUserProofStart(LogInfoUtil.getLogInfoPT("项目审核", data));
        }
        projectReviewMassageParam pro = new projectReviewMassageParam();
        pro.setProjectId(param.getProjectId());
        pro.setStatus(param.getAuditStatus());
        pro.setText(param.getRemark());
        rabbitTemplate.convertAndSend(MQConstant.PROJECT_AUDIT_QUEUE, pro);
    }

    @Override
    @Transactional
    public List<Project> getNoAuditProject(NoAuditProjectParam param) {
        Result<List<Project>> data = new Result<>();
        data = httpRequestUtil.postRequest("/hou/project/getNoAuditProject", param, data, Result.class);
        return data.getData();
    }

}
